// ---------------------------------------------------------------------------------------------------------------------------------
// Letter Control File for PCMod
// [CLIENTSIDE]
// Revision: 1
// ---------------------------------------------------------------------------------------------------------------------------------

// ---------------------------------------------------------------------------------------------------------------------------------
// pc_setupletter: Initialise Hook: Creates the derma stuff for the letter entity
// ---------------------------------------------------------------------------------------------------------------------------------
function pc_setupletter()
	local w = ScrW()
	local h = ScrH()
	local pn = vgui.Create( "DPanel" )
		pn:SetPos( w * 0.2, h * 0.2 )
		pn:SetSize( w * 0.6, h * 0.6 )
		pn.Paint = function( self )
			if (!self.Show) then return end
			surface.SetDrawColor( 255, 255, 255, 255 )
			surface.DrawRect( 0, 0, self:GetWide(), self:GetTall() )
			local text = SplitText( self.Text, self:GetWide()/6 )
			for k, v in pairs( text ) do
				local y = 4+((k-1)*20)
				local txt = string.Replace( v, "#", "" )
				draw.SimpleText( txt, "LetterText", 5, y, Color( 0, 0, 0, 255 ), TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP )
			end
		end
		pn.Show = false
		pn:SetVisible( false )
	PCMod.Letter = pn		
	local btn = vgui.Create( "DButton" )
	btn:SetParent( pn )
	btn:SetText( "X" )
	btn:SetPos( pn:GetWide()-20, 0 )
	btn:SetSize( 20, 20 )
	btn.DoClick = function()
		PCMod.Letter.Show = false
		PCMod.Letter:SetVisible( false )
		gui.EnableScreenClicker( false )
	end
end

// ---------------------------------------------------------------------------------------------------------------------------------
// pc_showletter: UserMessage Hook: Shows the letter upon notification of server
// ---------------------------------------------------------------------------------------------------------------------------------
function pc_showletter( um )
	PCMod.Letter.Text = um:ReadString()
	PCMod.Letter.Show = true
	PCMod.Letter:SetVisible( true )
	gui.EnableScreenClicker( true )
end
usermessage.Hook( "_pcmod_letter", pc_showletter )

// ---------------------------------------------------------------------------------------------------------------------------------
// SplitText: Splits a string into a table of evenly sized cunks
// ---------------------------------------------------------------------------------------------------------------------------------
function SplitText( txt, chunksize )
	local res = {}
	local id = 1
	local lid = 0
	for k, v in pairs( string.Explode( "", txt ) ) do
		lid = lid + 1
		if ((lid > chunksize) || (v == "#")) then
			id = id + 1
			lid = 0
		end
		if (!res[ id ]) then res[ id ] = "" end
		res[ id ] = res[ id ] .. v
	end
	return res
end